import React, { useState, useEffect, useCallback } from 'react'
import { SimpleSelector } from './simpleSelector'
import { getAllAjaxsOfPage } from '../../source/getData'
import { notify } from '../../source/notify'
import { NotifyType } from '../../common/enums'
import { ITEM_TITLE_MAX_LENGTH, ITEM_TITLE2_MAX_LENGTH } from '../../common/consts'

export const AjaxSelector = ({ placeholder = '', page, ajaxId, onSelectItem, readOnly = false }) => {
    const [dataSource, setDataSource] = useState([])
    const filterDataSource = useCallback(value => item => {
        const upperCaseValue = value.toUpperCase()
        return item.url.toUpperCase().includes(upperCaseValue) || item.remark.toUpperCase().includes(upperCaseValue)
    }, [])
    const getItemValue = useCallback(item => item.id, [])
    const renderItem = useCallback(item => `${item.url.substring(0, ITEM_TITLE_MAX_LENGTH)}[${item.remark.substring(0, ITEM_TITLE2_MAX_LENGTH)}]`, [])

    useEffect(() => {
        getAllAjaxsOfPage(page)
            .then(data => setDataSource(data))
            .catch(err => notify(NotifyType.error, err))
    }, [page])

    return <SimpleSelector dataSource={dataSource} filterDataSource={filterDataSource}
        getItemValue={getItemValue} initValue={ajaxId} onSelectItem={onSelectItem}
        readOnly={readOnly} renderItem={renderItem} placeholder={placeholder} />
}